const crypto = require('crypto');
const { query } = require('../config/mockDatabase');

class Coupon {
  constructor(data = {}) {
    // 基础字段
    this.coupon_id = data.coupon_id || null;
    this.title = data.title || '';
    this.description = data.description || '';
    this.remarks = data.remarks || '';
    
    // 优惠信息
    this.discount_type = data.discount_type || 'amount'; // amount, percent, free
    this.discount_value = data.discount_value || 0;
    this.minimum_order_amount = data.minimum_order_amount || 0;
    this.maximum_discount_amount = data.maximum_discount_amount || null;
    
    // 有效期设置
    this.validity_type = data.validity_type || 'absolute'; // absolute, relative
    this.valid_from = data.valid_from || null;
    this.valid_until = data.valid_until || null;
    this.validity_days = data.validity_days || null;
    
    // 使用限制
    this.usage_limit_per_user = data.usage_limit_per_user || 1;
    this.total_usage_limit = data.total_usage_limit || null;
    
    // JSON规则字段
    this.eligibility_rules = data.eligibility_rules || {};
    this.inclusion_rules = data.inclusion_rules || {};
    this.exclusion_rules = data.exclusion_rules || {};
    this.time_windows = data.time_windows || {};
    
    // 状态和统计
    this.status = data.status || 'active'; // active, inactive, expired, draft
    this.total_issued = data.total_issued || 0;
    this.total_used = data.total_used || 0;
    
    // 审计字段
    this.created_by = data.created_by || null;
    this.updated_by = data.updated_by || null;
    this.created_at = data.created_at || null;
    this.updated_at = data.updated_at || null;
    this.deleted_at = data.deleted_at || null;
  }

  /**
   * 验证优惠券数据
   */
  async validate() {
    const errors = [];
    
    if (!this.title || this.title.trim().length === 0) {
      errors.push('标题不能为空');
    }
    
    if (!['amount', 'percent', 'free'].includes(this.discount_type)) {
      errors.push('优惠类型必须是 amount, percent 或 free');
    }
    
    if (!this.validateDiscountValue()) {
      errors.push('优惠值不合法');
    }
    
    if (!['absolute', 'relative'].includes(this.validity_type)) {
      errors.push('有效期类型必须是 absolute 或 relative');
    }
    
    if (this.validity_type === 'absolute') {
      if (!this.valid_from || !this.valid_until) {
        errors.push('绝对有效期必须设置开始和结束时间');
      }
    } else if (this.validity_type === 'relative') {
      if (!this.validity_days || this.validity_days <= 0) {
        errors.push('相对有效期必须设置有效天数');
      }
    }
    
    if (errors.length > 0) {
      throw new Error('数据验证失败: ' + errors.join(', '));
    }
  }

  /**
   * 验证优惠值的合法性
   */
  validateDiscountValue() {
    switch (this.discount_type) {
      case 'amount':
        return this.discount_value && this.discount_value >= 0;
      case 'percent':
        return this.discount_value && this.discount_value >= 0 && this.discount_value <= 100;
      case 'free':
        return !this.discount_value || this.discount_value === 0;
      default:
        return false;
    }
  }

  /**
   * 检查是否在有效期内
   */
  isValid(referenceDate = new Date()) {
    if (this.status !== 'active') return false;
    
    if (this.validity_type === 'absolute') {
      const now = referenceDate;
      if (this.valid_from && now < new Date(this.valid_from)) return false;
      if (this.valid_until && now > new Date(this.valid_until)) return false;
    }
    
    return true;
  }

  /**
   * 生成规则哈希值
   */
  generateEligibilityHash() {
    const rules = {
      eligibility_rules: this.eligibility_rules,
      inclusion_rules: this.inclusion_rules,
      exclusion_rules: this.exclusion_rules,
      time_windows: this.time_windows
    };
    
    const rulesString = JSON.stringify(rules, Object.keys(rules).sort());
    return crypto.createHash('sha256').update(rulesString).digest('hex');
  }

  /**
   * 创建新的优惠券
   */
  static async create(couponData, createdBy = null) {
    try {
      const coupon = new Coupon({
        ...couponData,
        created_by: createdBy,
        updated_by: createdBy,
        created_at: new Date().toISOString(),
        updated_at: new Date().toISOString()
      });

      // 验证数据
      await coupon.validate();

      // 生成哈希值
      const eligibilityHash = coupon.generateEligibilityHash();

      // 插入到模拟数据库
      const insertSql = `
        INSERT INTO coupons (
          title, description, discount_type, discount_value, minimum_order_amount,
          maximum_discount_amount, validity_type, valid_from, valid_until, validity_days,
          usage_limit_per_user, total_usage_limit, status, remarks,
          eligibility_rules, inclusion_rules, exclusion_rules, time_windows,
          total_issued, total_used, created_by, updated_by, created_at, updated_at
        ) VALUES (
          '${coupon.title}', '${coupon.description}', '${coupon.discount_type}', ${coupon.discount_value},
          ${coupon.minimum_order_amount}, ${coupon.maximum_discount_amount || 'NULL'},
          '${coupon.validity_type}', '${coupon.valid_from || ''}', '${coupon.valid_until || ''}', ${coupon.validity_days || 'NULL'},
          ${coupon.usage_limit_per_user}, ${coupon.total_usage_limit || 'NULL'}, '${coupon.status}', '${coupon.remarks}',
          '${JSON.stringify(coupon.eligibility_rules)}', '${JSON.stringify(coupon.inclusion_rules)}',
          '${JSON.stringify(coupon.exclusion_rules)}', '${JSON.stringify(coupon.time_windows)}',
          ${coupon.total_issued}, ${coupon.total_used}, ${coupon.created_by || 'NULL'}, ${coupon.updated_by || 'NULL'},
          '${coupon.created_at}', '${coupon.updated_at}'
        )
      `;

      const result = await query(insertSql);
      coupon.coupon_id = result.insertId;

      console.log(`优惠券创建成功: ${coupon.title} (ID: ${coupon.coupon_id})`);
      return coupon;
    } catch (error) {
      console.error('创建优惠券失败:', error);
      throw error;
    }
  }

  /**
   * 根据ID查找优惠券
   */
  static async findById(couponId) {
    try {
      const sql = `SELECT * FROM coupons WHERE coupon_id = ${couponId} AND deleted_at IS NULL`;
      const result = await query(sql);
      
      if (result.length === 0) {
        return null;
      }
      
      const data = result[0];
      // 解析JSON字段
      if (data.eligibility_rules) data.eligibility_rules = JSON.parse(data.eligibility_rules);
      if (data.inclusion_rules) data.inclusion_rules = JSON.parse(data.inclusion_rules);
      if (data.exclusion_rules) data.exclusion_rules = JSON.parse(data.exclusion_rules);
      if (data.time_windows) data.time_windows = JSON.parse(data.time_windows);
      
      return new Coupon(data);
    } catch (error) {
      console.error('查找优惠券失败:', error);
      throw error;
    }
  }

  /**
   * 解析优惠字符串
   */
  static parseDiscountString(discountStr) {
    if (!discountStr || typeof discountStr !== 'string') {
      throw new Error('Invalid discount string');
    }
    
    const str = discountStr.trim().toLowerCase();
    
    // Free券
    if (str === 'free') {
      return { type: 'free', value: 0 };
    }
    
    // 金额券：S$X off
    const amountMatch = str.match(/^s\$([0-9]+(?:\.[0-9]{1,2})?)\s*off$/i);
    if (amountMatch) {
      return { type: 'amount', value: parseFloat(amountMatch[1]) };
    }
    
    // 折扣券：X% off
    const percentMatch = str.match(/^([0-9]+(?:\.[0-9]{1,2})?)%\s*off$/i);
    if (percentMatch) {
      const percent = parseFloat(percentMatch[1]);
      if (percent < 0 || percent > 100) {
        throw new Error('Percentage must be between 0 and 100');
      }
      return { type: 'percent', value: percent };
    }
    
    throw new Error(`Unable to parse discount string: ${discountStr}`);
  }

  /**
   * 分页查询优惠券
   */
  static async findAll(options = {}) {
    try {
      const { page = 1, limit = 20, status, discount_type } = options;
      const offset = (page - 1) * limit;
      
      let whereClause = 'WHERE deleted_at IS NULL';
      if (status) {
        whereClause += ` AND status = '${status}'`;
      }
      if (discount_type) {
        whereClause += ` AND discount_type = '${discount_type}'`;
      }
      
      const sql = `
        SELECT * FROM coupons 
        ${whereClause}
        ORDER BY created_at DESC 
        LIMIT ${limit} OFFSET ${offset}
      `;
      
      const results = await query(sql);
      
      return results.map(data => {
        // 解析JSON字段
        if (data.eligibility_rules) data.eligibility_rules = JSON.parse(data.eligibility_rules);
        if (data.inclusion_rules) data.inclusion_rules = JSON.parse(data.inclusion_rules);
        if (data.exclusion_rules) data.exclusion_rules = JSON.parse(data.exclusion_rules);
        if (data.time_windows) data.time_windows = JSON.parse(data.time_windows);
        
        return new Coupon(data);
      });
    } catch (error) {
      console.error('查询优惠券列表失败:', error);
      throw error;
    }
  }

  /**
   * 获取优惠券统计数据
   * @param {Object} options - 查询选项
   * @param {string} options.start_date - 开始日期
   * @param {string} options.end_date - 结束日期
   * @returns {Object} 统计数据
   */
  static async getStats(options = {}) {
    try {
      console.log('🔍 Mock DB Query: Coupon.getStats');
      
      // 模拟数据库查询延迟
      await new Promise(resolve => setTimeout(resolve, 30));
      
      // 返回模拟统计数据
      return {
        total: 15,
        active: 12,
        used: 8,
        expired: 2,
        usage_rate: 53.3,
        total_discount_amount: 1250.00
      };
    } catch (error) {
      console.error('Error in Coupon.getStats:', error);
      throw error;
    }
  }
}

module.exports = Coupon;